package com.yy.logic.impl;

import com.yy.logic.ICompanyLogic;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yy.dao.ICompanyDAO;
import com.yy.model.TbCompany;
import com.yy.model.TbUser;
import com.yy.dto.CompanyDTO;

@Component
public class CompanyLogic implements ICompanyLogic{
	@Resource
	private ICompanyDAO companyDAO;
	
	@Transactional
	@Override
	public JSONObject getAllCompany()throws Exception{
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		int count = 0;
		try{
			List<TbCompany> listCompanyBean = this.companyDAO.getAllCompany(); 
			count = this.companyDAO.getCompanyCount();
			List<CompanyDTO> listCompanyDTO = new ArrayList<CompanyDTO>();
			Iterator<TbCompany> itrCompanyBean = listCompanyBean.iterator();
			while(itrCompanyBean.hasNext()){
				TbCompany objCompanyBean = (TbCompany) itrCompanyBean.next();
				listCompanyDTO.add(objCompanyBean.toDTO());
			}
			jsonMap.put("data", listCompanyDTO);
			jsonMap.put("num",count);
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return JSONObject.fromObject(jsonMap);
	}
	
	@Transactional
	@Override
	public String companyCheck(String companylogin,String comPwd) throws Exception {
		// TODO Auto-generated method stub
		String result = "对不起，系统错误！";
		try {
			List<TbCompany> userlist = companyDAO.CompanyLogin(companylogin);
			System.out.println(userlist.get(0).getCompanyManPwd());
			if (userlist == null) {
				result = "对不起，数据库错误！";
			} else if (userlist.size() == 0) {
				result = "对不起，用户名错误！";
			} else {
				TbCompany userbean = (TbCompany) userlist.get(0);
				if (!comPwd.equals(userbean.getCompanyManPwd())) {
					result = "对不起，密码错误！";
				} else {
					
					System.out.println("login");
					HttpServletRequest request = ServletActionContext
							.getRequest();
					HttpSession loginusersession = request.getSession();
					//System.out.println("userList---->"
					//		+ userlist.get(0).getTbCompany().getCompanyName());
					loginusersession.setAttribute("loginCompanySession",
							userlist.get(0).getCompanyManName());// 设置登录成功用户Session
					//Map<Integer,TbUser> userMap = new HashMap<Integer,TbUser>();
					//int size = userlist.size();
					//System.out.println("********userlist*********+"+size);
					//for(int i=0;i<size;i++){
					//	TbUser userBean = userlist.get(i);
					//	userMap.put(userBean.getUserId(),userBean);
					//}
					//loginusersession.setAttribute(SessionConstants.SESSION_LOGIN_USER, userMap);
					result = "PASS";
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "对不起，系统错误！";
		}
		return result;
	}
}
